import dotenv from 'dotenv';
import path from 'path';
import { logger } from './logger';

// 加载环境变量
const envPath = path.resolve(process.cwd(), '.env.development');
logger.info('加载环境变量:', { 路径: envPath });

const result = dotenv.config({
  path: envPath
});

if (result.error) {
  logger.error('环境变量加载失败:', { 错误信息: result.error.message });
  throw result.error;
}

logger.info('环境变量加载成功');

// 环境变量配置接口
interface EnvConfig {
  gitlab: {
    repository: string;
    branch: string;
    username: string;
    token: string;
    sshKey?: string;
  };
  storage: {
    repositoryPath: string;
    reportPath: string;
    logPath: string;
  };
  task: {
    timeout: number;
  };
  log: {
    level: string;
    format: string;
  };
}

// 验证必要的环境变量
function validateEnv(): void {
  const requiredEnvVars = [
    'GITLAB_REPOSITORY',
    'GITLAB_BRANCH',
    'GITLAB_TOKEN',
    'GITLAB_USERNAME',
    'STORAGE_REPOSITORY_PATH',
    'STORAGE_REPORT_PATH',
    'STORAGE_LOG_PATH',
    'TASK_TIMEOUT',
    'LOG_LEVEL',
    'LOG_FORMAT'
  ];

  const missingEnvVars = requiredEnvVars.filter(envVar => !process.env[envVar]);

  if (missingEnvVars.length > 0) {
    logger.error('缺少必需的环境变量:', { 缺失变量: missingEnvVars });
    throw new Error(`Missing required environment variables: ${missingEnvVars.join(', ')}`);
  }

  logger.info('所有必需的环境变量已就绪');
}

// 验证环境变量
validateEnv();

// 导出环境变量配置
export const env: EnvConfig = {
  gitlab: {
    repository: process.env.GITLAB_REPOSITORY!,
    branch: process.env.GITLAB_BRANCH!,
    username: process.env.GITLAB_USERNAME!,
    token: process.env.GITLAB_TOKEN!,
    sshKey: process.env.GITLAB_SSH_KEY
  },
  storage: {
    repositoryPath: process.env.STORAGE_REPOSITORY_PATH!,
    reportPath: process.env.STORAGE_REPORT_PATH!,
    logPath: process.env.STORAGE_LOG_PATH!
  },
  task: {
    timeout: parseInt(process.env.TASK_TIMEOUT!, 10)
  },
  log: {
    level: process.env.LOG_LEVEL!,
    format: process.env.LOG_FORMAT!
  }
};

// 输出配置信息（不包含敏感信息）
logger.info('环境配置已加载:', {
  gitlab: {
    repository: env.gitlab.repository,
    branch: env.gitlab.branch,
    username: env.gitlab.username
  },
  storage: env.storage,
  task: env.task,
  log: env.log
}); 